package com.linking.controller.filter;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.linking.controller.configuration.WrappedRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

/**
 * @Author YaoWeiXin
 * @Date 2019/11/1 11:38
 * @Description 基础过滤类
 */
@Slf4j
public abstract class BaseFilter {

  public static String prefixStr = "/s/";
  public static List<String> pathList = Lists.newArrayList();

  protected WrappedRequest getRequest(ServletRequest sRequest) throws IOException {
    return new WrappedRequest((HttpServletRequest) sRequest);
  }

  protected HttpServletResponse getResponse(ServletResponse sResponse) {
    HttpServletResponse response = (HttpServletResponse) sResponse;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "*");
    response.setHeader("Access-Control-Allow-Headers",
        "Content-Type,XFILENAME,XFILECATEGORY,XFILESIZE");
    return response;
  }

  /**
   * 测试是否是OPTIONS请求，如果是返回OPTIONS returns OK
   */
  protected Boolean testInOptions(WrappedRequest request, HttpServletResponse response)
      throws IOException {
    String optionsStr = "OPTIONS";
    if (optionsStr.equals(request.getMethod())) {
      response.setStatus(HttpStatus.OK.value());
      response.getWriter().write("OPTIONS returns OK");
      return true;
    } else {
      return false;
    }
  }

  protected JSONObject getBodyJson(HttpServletRequest request) throws IOException {
    String body = IoUtil.read(request.getReader());
    return JSON.parseObject(body);
  }

  protected void printResult(ServletResponse response, String res) {
    response.setContentType("text/plain;charset=utf-8");
    try (PrintWriter printWriter = response.getWriter()) {
      printWriter.write(res);
      printWriter.flush();
    } catch (Exception e) {
      log.error("printResult error = {0}", e);
    }
  }
}
